#!/bin/bash

# 设置路径
NDK_ROOT="/mnt/android_home/ndk/r21e"
LAME_ROOT="$(pwd)"
BUILD_DIR="${LAME_ROOT}/build-android"

# 检查 NDK 路径
if [ ! -d "$NDK_ROOT" ]; then
    echo "❌ NDK 路径不存在: $NDK_ROOT"
    exit 1
fi

# 支持的架构列表
ARCHS=("arm64-v8a" "armeabi-v7a" "x86_64" "x86")
ABIS=("aarch64-linux-android" "armv7a-linux-androideabi" "x86_64-linux-android" "i686-linux-android")
APIS=(21 19 21 19)
CLANGS=("clang" "clang" "clang" "clang")

# 创建输出目录
mkdir -p "$BUILD_DIR"

echo "🚀 开始编译 MP3LAME for Android"
cd /opt/module/src/mp3lame/main
for i in "${!ARCHS[@]}"; do
    ARCH="${ARCHS[$i]}"
    ABI="${ABIS[$i]}"
    API="${APIS[$i]}"
    CLANG="${CLANGS[$i]}"

    echo "──────────────────────────────"
    echo "📦 正在编译: $ARCH (API $API)"

    # 设置工具链路径
    TOOLCHAIN="$NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin"
    CC="$TOOLCHAIN/$CLANG"
    CXX="$TOOLCHAIN/${CLANG}++"
    SYSROOT="$NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/sysroot"

    # 编译目标目录
    OUTPUT_DIR="$BUILD_DIR/$ARCH"
    mkdir -p "$OUTPUT_DIR"

    # 清理旧构建
    make clean || true

    # 配置交叉编译
    ./configure \
        --host=$ABI \
        --target=$ABI \
        --enable-static \
        --disable-shared \
        --disable-frontend \
        --with-sysroot="$SYSROOT" \
        --prefix="$OUTPUT_DIR" \
        CC="$CC" \
        CXX="$CXX" \
        CFLAGS="--target=${ABI}${API} -I$SYSROOT/usr/include -fPIC -O2" \
        LDFLAGS="--target=${ABI}${API} -L$SYSROOT/usr/lib"

    # 编译并安装
    make -j$(nproc) && make install
    if [ $? -eq 0 ]; then
        echo "✅ $ARCH 编译成功 -> $OUTPUT_DIR"
    else
        echo "❌ $ARCH 编译失败"
        exit 1
    fi
done

echo "🎉 所有架构编译完成！"
echo "📁 输出目录: $BUILD_DIR"

